import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_easyrefresh/material_footer.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:jspang/model/category.dart';
import 'package:jspang/model/categoryGoodsList.dart';
import 'package:jspang/provide/category_goods_list.dart';
import 'package:jspang/provide/child_category.dart';
import 'package:jspang/service/service_method.dart';
import 'package:provider/provider.dart';

class CategoryPage extends StatefulWidget {
  CategoryPage({Key key}) : super(key: key);

  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('商品分类'),
        centerTitle: true,
      ),
      body: Container(
        child: Row(
          children: <Widget>[
            LeftCategoryNav(),
            Column(
              children: <Widget>[RightCategoryNav(), CategoryGoodsList()],
            )
          ],
        ),
      ),
    );
  }
}

//左侧大类导航
class LeftCategoryNav extends StatefulWidget {
  LeftCategoryNav({Key key}) : super(key: key);

  @override
  _LeftCategoryNavState createState() => _LeftCategoryNavState();
}

class _LeftCategoryNavState extends State<LeftCategoryNav> {
  List list = [];
  var listIndex = 0;
  @override
  void initState() {
    _getCategory();
    _getGoodsList();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        width: ScreenUtil().setWidth(180),
        decoration: BoxDecoration(
            border: Border(right: BorderSide(width: 1, color: Colors.black12))),
        child: ListView.builder(
          itemCount: list.length,
          itemBuilder: (context, index) {
            return _leftInkWell(index);
          },
        ));
  }

  Widget _leftInkWell(int index) {
    bool isClick = false;
    isClick = (index == listIndex) ? true : false;
    return Selector<ChildCategory, ChildCategory>(
        selector: (context, provider) => provider,
        shouldRebuild: (pre, next) => true,
        builder: (context, childcategory, child) {
          return InkWell(
            onTap: () {
              setState(() {
                listIndex = index;
              });
              var childList = list[index].bxMallSubDto;
              var categoryId = list[index].mallCategoryId;
              childcategory.getChildCategory(childList, categoryId);
              _getGoodsList(categoryId: categoryId);
            },
            child: Container(
              height: ScreenUtil().setHeight(100),
              padding: EdgeInsets.only(
                left: 10.0,
                top: 15.0,
              ),
              decoration: BoxDecoration(
                  color: isClick
                      ? Color.fromRGBO(236, 236, 236, 1.0)
                      : Colors.white,
                  border: Border(
                      bottom: BorderSide(width: 1, color: Colors.black12))),
              child: Text(
                list[index].mallCategoryName,
                style: TextStyle(fontSize: ScreenUtil().setSp(28)),
              ),
            ),
          );
        });
  }

  void _getCategory() async {
    await request('getCategory').then((val) {
      var data = json.decode(val.toString());
      CategoryModel category = CategoryModel.fromJson(data);
      setState(() {
        list = category.data;
      });
      // ChildCategory(context).getChildCategory(list[0].bxMallSubDto);
      Provider.of<ChildCategory>(context, listen: false)
          .getChildCategory(list[0].bxMallSubDto, list[0].mallCategoryId);
    });
  }

  void _getGoodsList({String categoryId}) async {
    var data = {
      "categoryId": categoryId == null ? '4' : categoryId,
      "categorySubId": '',
      "page": 1,
    };
    await request('getMallGoods', formData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      Provider.of<CategoryGoodsListProvider>(context, listen: false)
          .getGoodsList(goodsList.data);
    });
  }
}

//右侧
class RightCategoryNav extends StatefulWidget {
  RightCategoryNav({Key key}) : super(key: key);

  @override
  _RightCategoryNavState createState() => _RightCategoryNavState();
}

class _RightCategoryNavState extends State<RightCategoryNav> {
  // List list = ['名酒', '宝丰', '北京二锅头', '舍得', '五粮液', '茅台'];
  @override
  Widget build(BuildContext context) {
    return Selector<ChildCategory, ChildCategory>(
      selector: (context, provider) => provider,
      shouldRebuild: (pre, next) => true,
      builder: (context, childcategory, child) {
        return Container(
          height: ScreenUtil().setHeight(80),
          width: ScreenUtil().setWidth(570),
          decoration: BoxDecoration(
              color: Colors.white,
              border:
                  Border(bottom: BorderSide(width: 1, color: Colors.black12))),
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: childcategory.childCategoryList.length,
            itemBuilder: (context, index) {
              return _rightInkWell(
                  index, childcategory.childCategoryList[index]);
            },
          ),
        );
      },
    );
  }

  Widget _rightInkWell(int index, BxMallSubDto item) {
    bool isClick = false;
    isClick = (index == Provider.of<ChildCategory>(context).childIndex)
        ? true
        : false;

    return InkWell(
      onTap: () {
        Provider.of<ChildCategory>(context, listen: false)
            .changechildIndex(index, item.mallSubId);
        _getGoodsList(item.mallSubId);
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.mallSubName,
          style: TextStyle(
              fontSize: ScreenUtil().setSp(28),
              color: isClick ? Colors.pink : Colors.black),
        ),
      ),
    );
  }

  void _getGoodsList(String categorySubId) async {
    var data = {
      "categoryId":
          Provider.of<ChildCategory>(context, listen: false).categoryId,
      "categorySubId": categorySubId,
      "page": 1,
    };
    await request('getMallGoods', formData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      if (goodsList.data == null) {
        Provider.of<CategoryGoodsListProvider>(context, listen: false)
            .getGoodsList([]);
      } else {
        Provider.of<CategoryGoodsListProvider>(context, listen: false)
            .getGoodsList(goodsList.data);
      }
    });
  }
}

//商品列表 ，可以上拉加载
class CategoryGoodsList extends StatefulWidget {
  CategoryGoodsList({Key key}) : super(key: key);

  @override
  _CategoryGoodsListState createState() => _CategoryGoodsListState();
}

class _CategoryGoodsListState extends State<CategoryGoodsList> {
  // List list = [];
  var scorllController = new ScrollController();
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Expanded(
        child: Selector<CategoryGoodsListProvider, CategoryGoodsListProvider>(
      selector: (context, provoder) => provoder,
      shouldRebuild: (pre, next) => true,
      builder: (context, goodsListProvider, child) {
        try {
          if (Provider.of<ChildCategory>(context).page == 1) {
            //列表位置，放到最上边
            scorllController.jumpTo(0.0);
          }
        } catch (e) {
          print('进入页面第一次初始化');
        }
        if (goodsListProvider.goodsList.length > 0) {
          return Container(
            width: ScreenUtil().setWidth(570),
            child: EasyRefresh(
              footer: MaterialFooter(),
              child: ListView.builder(
                controller: scorllController,
                itemCount: goodsListProvider.goodsList.length,
                itemBuilder: (context, index) {
                  return _listWidget(goodsListProvider.goodsList, index);
                },
              ),
              onLoad: () async {
                print('上拉加载更多');
                _getMoreList();
              },
            ),
          );
        } else {
          return Text('暂时没有数据');
        }
      },
    ));
  }

  void _getMoreList() async {
    Provider.of<ChildCategory>(context, listen: false).addPage();
    var data = {
      "categoryId":
          Provider.of<ChildCategory>(context, listen: false).categoryId,
      "categorySubId": Provider.of<ChildCategory>(context, listen: false).subId,
      "page": Provider.of<ChildCategory>(context, listen: false).page,
    };
    await request('getMallGoods', formData: data).then((val) {
      var data = json.decode(val.toString());
      CategoryGoodsListModel goodsList = CategoryGoodsListModel.fromJson(data);
      if (goodsList.data == null) {
        Fluttertoast.showToast(
            msg: "没有更多了",
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
            timeInSecForIosWeb: 1,
            backgroundColor: Colors.pink,
            textColor: Colors.white,
            fontSize: 16.0);
        Provider.of<ChildCategory>(context, listen: false)
            .changeNoMoreText('没有更多了');
      } else {
        Provider.of<CategoryGoodsListProvider>(context, listen: false)
            .getModeList(goodsList.data);
      }
    });
  }

  //图片区域
  Widget _goodsImage(List newList, index) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(newList[index].image),
    );
  }

  //商品名称
  Widget _goodsName(List newList, index) {
    return Container(
      padding: EdgeInsets.all(5.0),
      width: ScreenUtil().setWidth(370),
      child: Text(
        newList[index].goodsName,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  //价格区域
  Widget _goodsPrice(List newList, index) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Text(
            '价格:￥${newList[index].presentPrice}',
            style:
                TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(30)),
          ),
          Text(
            '价格:￥${newList[index].oriPrice}',
            style: TextStyle(
                color: Colors.black26, decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  Widget _listWidget(List newList, int index) {
    return InkWell(
      onTap: () {},
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Row(
          children: <Widget>[
            _goodsImage(newList, index),
            Column(
              children: <Widget>[
                _goodsName(newList, index),
                _goodsPrice(newList, index)
              ],
            )
          ],
        ),
      ),
    );
  }
}
